﻿; (function($) {
	// Private functions.
	var p = {};
	p.onHide = function(hash) {
		var $modalWindow = $(hash.w);
		$modalWindow.fadeOut('2000', function() {
			hash.o.remove();
			//refresh parent
			if (hash.refreshAfterClose) {
				window.location.reload();
			};
		});

	};
	p.onShow = function(hash) {
		var $trigger = $(hash.t);
		var $modalWindow = hash.w;
		var $modalContainer = $('iframe', $modalWindow);
		var myUrl = $trigger.attr('href');
		var myTitle = $trigger.attr('title');
		$modalContainer.html('').attr('src', myUrl);
		$('.jqmTitleText', hash.w).text(myTitle);
		var anchorStr = (myUrl.indexOf("#") > -1) ? myUrl.substr(myUrl.indexOf("#") + 1) : null;
		var dim = { width: $modalWindow.width(), height: $modalWindow.height(), left: 0, top: 0, refresh: false };
		if (anchorStr) {
			var anchorObj = $.evalJSON(anchorStr);
			dim = $.extend({}, dim, anchorObj);
			hash.refreshAfterClose = dim.refresh;
			//height
			if (dim.height == 0) { dim.height = $modalWindow.height(); } else {
				if (dim.height.indexOf('%') > -1) {
					dim.height = Math.floor(parseInt($(window).height()) * (parseInt(dim.height) / 100));
				};
				dim.top = Math.floor(parseInt($(window).height() - dim.height) / 2);
			};
			//width
			if (dim.width != 0) {
				if (dim.width.indexOf('%') > -1) {
					dim.width = Math.floor(parseInt($(window).width() / 100) * parseInt(dim.width));
				}
				dim.left = Math.floor(parseInt($(window).width() / 2) - parseInt(dim.width) / 2);
			}
			else {
				dim.width = $modalWindow.width();
			};
			//show the jqModal
			// do the animation so that the windows stays on center of screen despite resizing
			$modalWindow.css({
				width: dim.width,
				height: dim.height,
				opacity: 0.3,
				top: dim.top,
				left: dim.left
			}).jqmShow().animate({
				width: dim.width,
				height: dim.height,
				top: dim.top,
				left: dim.left,
				marginLeft: 0,
				opacity: 1
			}, p.opts.showSpeed || 'normal');
		} else {
			$modalWindow.css({ width: dim.width, height: dim.height }).jqmShow();
		};
	};

	//main plugin body
	$.fn.jqModalFrame = function(options) {
		// Set the options.
		options = $.extend({}, $.fn.jqModalFrame.defaults, options);
		p.opts = options;
		// Go through the matched elements and return the jQuery object.
		return this.each(function() {
			var Obj = this;
			$(Obj).jqm(options);
		});
	};
	// Public defaults.	convenient for global overrides.
	$.fn.jqModalFrame.defaults = {
		overlay: 70,
		modal: true,
		trigger: '.action',
		target: ".jqmContent",
		webRoot: "",
		onHide: p.onHide,
		onShow: p.onShow
	};
})(jQuery);
